package com.hzdesk.media.koreabatchmatvector.logic.view;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hzdesk.media.koreabatchmatvector.R;
import com.hzdesk.media.koreabatchmatvector.adapter.WiFiSettingAdapter;
import com.hzdesk.media.koreabatchmatvector.bean.WifiBean;
import com.hzdesk.media.koreabatchmatvector.config.AppContants;
import com.hzdesk.media.koreabatchmatvector.custom.WifiSupport;
import com.hzdesk.media.koreabatchmatvector.custom.myProgressBar;
import com.hzdesk.media.koreabatchmatvector.dialog.WifiLinkDialog;
import com.hzdesk.media.koreabatchmatvector.inter.IWifiLinkDialogInter;
import com.hzdesk.media.koreabatchmatvector.inter.OnclikedWiFiSetting;
import com.hzdesk.media.koreabatchmatvector.logic.contract.INewWiFiSettingContract;
import com.hzdesk.media.koreabatchmatvector.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/2.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class NewWiFiSettingActivity extends BaseActivity implements INewWiFiSettingContract.INewWiFiSettingView {
    @BindView(R.id.activity_new_wifi_setting_iv_back)
    ImageView activityNewWifiSettingIvBack;
    @BindView(R.id.activity_new_wifi_setting_iv_close)
    ImageView activityNewWifiSettingIvClose;
    @BindView(R.id.activity_new_wifi_setting_my_preogress)
    myProgressBar activityNewWifiSettingMyPreogress;
    @BindView(R.id.aactivity_new_wifi_setting_recyclerview)
    RecyclerView aactivityNewWifiSettingRecyclerview;
    @BindView(R.id.activity_new_wifi_setting_ll_bg)
    LinearLayout activityNewWifiSettingLlBg;
    private WiFiSettingAdapter mWiFiSettingAdapter;

    private static final String TAG = "MainActivity";
    private int connectType = 0;//1：连接成功？ 2 正在连接（如果wifi热点列表发生变需要该字段）
    private WifiBroadcastReceiver wifiReceiver;
    private WifiManager mWifiManager;
    List<WifiBean> realWifiList = new ArrayList<>();
    //权限请求码
    private static final int PERMISSION_REQUEST_CODE = 0;
    private boolean mHasPermission;
    //两个危险权限需要动态申请
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_wifi_setting);
        ButterKnife.bind(this);

        activityNewWifiSettingMyPreogress.refresh();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        aactivityNewWifiSettingRecyclerview.setLayoutManager(layoutManager);
        mWiFiSettingAdapter = new WiFiSettingAdapter(this);
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()){  //已经打开了wifi
            showProgress();
          showOpen();
            //requestPermission(mContext);
          boolean flag =   checkPermission() ;
          if(!flag ||  !WifiSupport.isOpenWifi(this)){
              requestPermission();
          }
        }else{//没有打开了wifi
            hidenProgress();
          showcloase();
            // 清空容器wifi 信息
            clearAll();
        }
        mWiFiSettingAdapter.setmOnclikedWiFiSetting(new OnclikedWiFiSetting() {
            @Override
            public void onClickedItem(int postion) {
                wifiConnect(postion);
            }
        });


    }
    // 点击连接wifi
    private void wifiConnect(int postion) {
        WifiBean mWifiBean =   realWifiList.get(postion);
        if(mWifiBean != null ){
            if(WifiSupport.getWifiCipher(mWifiBean.getCapabilities())==WifiSupport.WifiCipherType.WIFICIPHER_NOPASS){ //无需密码
                WifiConfiguration tempConfig  = WifiSupport.isExsits(mWifiBean.getWifiName(),this);
                if(tempConfig == null){
                    WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mWifiBean.getWifiName(),null,WifiSupport.WifiCipherType.WIFICIPHER_NOPASS);
                    WifiSupport.addNetWork(wifiConfiguration,this);
                }else{
                    WifiSupport.addNetWork(tempConfig,this);
                }
            }else{   //需要密码，弹出输入密码dialog
                noConfigurationWifi(mWifiBean,this);
            }
        }
    }
    //之前没配置过该网络， 弹出输入密码界面
    private void noConfigurationWifi(WifiBean mWifiBean, final Context mContext) {
        final WifiLinkDialog linkDialog = new WifiLinkDialog(mContext, R.style.dialog_download,mWifiBean);
        if(!linkDialog.isShowing()){
            linkDialog.show();
        }
        linkDialog.setmIWifiLinkDialogInter(new IWifiLinkDialogInter() {
            @Override
            public void OnClickedDetermine(WifiBean mWifiBean, String inputPassword) {
                WifiConfiguration tempConfig = WifiSupport.isExsits(mWifiBean.getWifiName(),mContext);
                if (tempConfig == null) {
                    WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mWifiBean.getWifiName(),inputPassword, WifiSupport.getWifiCipher(mWifiBean.getCapabilities()));
                    WifiSupport.addNetWork(wifiConfiguration,mContext);
                } else {
                    WifiSupport.addNetWork(tempConfig, mContext);
                }
                linkDialog.dismiss();
                // todo 调整位置
                if(mWifiBean != null && mWifiBean != null){
                    realWifiList.remove(mWifiBean);
                    realWifiList.add(0,mWifiBean);
                    mWiFiSettingAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void OnClickedCancel() {
                linkDialog.dismiss();
            }
        });
    }
    @OnClick({R.id.activity_new_wifi_setting_iv_back, R.id.activity_new_wifi_setting_iv_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_new_wifi_setting_iv_back:
                WiFiSettingbacak();
                break;
            case R.id.activity_new_wifi_setting_iv_close:
                if (mWifiManager.isWifiEnabled()) {  //todo 关闭wifi
                   hidenProgress();
                    mWifiManager.setWifiEnabled(false);
                    showcloase();
                    // 清空容器wifi 信息
                    clearAll();
                }else{  //todo 打开wifi
                    showProgress();
                    mWifiManager.setWifiEnabled(true);
                    showOpen();
                    // todo 申请权限
                    boolean flag =   checkPermission() ;
                    if(!flag ||  !WifiSupport.isOpenWifi(this)){
                        requestPermission();
                    }
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册广播
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态广播,是否连接了一个有效路由
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        this.registerReceiver(wifiReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(wifiReceiver);
    }



    //监听wifi状态
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())){
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state){
                    /**
                     * WIFI_STATE_DISABLED    WLAN已经关闭
                     * WIFI_STATE_DISABLING   WLAN正在关闭
                     * WIFI_STATE_ENABLED     WLAN已经打开
                     * WIFI_STATE_ENABLING    WLAN正在打开
                     * WIFI_STATE_UNKNOWN     未知
                     */
                    case WifiManager.WIFI_STATE_DISABLED:{
                        Log.e(TAG,"已经关闭");
                        Toast.makeText(NewWiFiSettingActivity.this,"WIFI处于关闭状态",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING:{
                        Log.e(TAG,"正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED:{
                        Log.e(TAG,"已经打开============");
                        mWifiManager.startScan();
                        sortScaResult();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING:{
                        Log.e(TAG,"正在打开=================11111");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN:{
                        Log.e(TAG,"未知状态");
                        break;
                    }
                }
            }else if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())){
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.d(TAG, "--NetworkInfo--" + info.toString());
                if(NetworkInfo.State.DISCONNECTED == info.getState()){//wifi没连接上
                    Log.e(TAG,"wifi没连接上 ========1");

                    for(int i = 0;i < realWifiList.size();i++){//没连接上将 所有的连接状态都置为“未连接”
                        realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
                    }
                    mWiFiSettingAdapter.notifyDataSetChanged();
                }else if(NetworkInfo.State.CONNECTED == info.getState()){//wifi连接上了
                    Log.e(TAG,"wifi连接上了==========2222222222");
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(NewWiFiSettingActivity.this);
                    //连接成功 跳转界面 传递ip地址
                    Toast.makeText(NewWiFiSettingActivity.this,"wifi连接上了",Toast.LENGTH_SHORT).show();
                    connectType = 1;
                    wifiListSet(connectedWifiInfo.getSSID(),connectType);
                }else if(NetworkInfo.State.CONNECTING == info.getState()){//正在连接
                    Log.e(TAG,"wifi正在连接");
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(NewWiFiSettingActivity.this);
                    connectType = 2;
                    wifiListSet(connectedWifiInfo.getSSID(),connectType );
                }
            }else if(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())){
                Log.e(TAG,"网络列表变化了");
                wifiListChange();
            }
        }
    }
    /**
     * //网络状态发生改变 调用此方法！
     */
    public void wifiListChange(){
        sortScaResult();
        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(this);
        if(connectedWifiInfo != null){
            wifiListSet(connectedWifiInfo.getSSID(),connectType);
        }
    }

    /**
     * 将"已连接"或者"正在连接"的wifi热点放置在第一个位置
     * @param wifiName
     * @param type
     */
    public void wifiListSet(String wifiName , int type){
        int index = -1;
        WifiBean wifiInfo = new WifiBean();
        if(CollectionUtils.isNullOrEmpty(realWifiList)){
            return;
        }
        for(int i = 0;i < realWifiList.size();i++){
            realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
        }
        Collections.sort(realWifiList);//根据信号强度排序
        for(int i = 0;i < realWifiList.size();i++){
            WifiBean wifiBean = realWifiList.get(i);
            if(index == -1 && ("\"" + wifiBean.getWifiName() + "\"").equals(wifiName)){
                index = i;
                wifiInfo.setLevel(wifiBean.getLevel());
                wifiInfo.setWifiName(wifiBean.getWifiName());
                wifiInfo.setCapabilities(wifiBean.getCapabilities());
                if(type == 1){
                    wifiInfo.setState(AppContants.WIFI_STATE_CONNECT);
                }else{
                    wifiInfo.setState(AppContants.WIFI_STATE_ON_CONNECTING);
                }
            }
        }
        if(index != -1){
            realWifiList.remove(index);
            realWifiList.add(0, wifiInfo);
            mWiFiSettingAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取wifi列表然后将bean转成自己定义的WifiBean
     */
    public void sortScaResult(){
        List<ScanResult> scanResults = WifiSupport.noSameName(WifiSupport.getWifiScanResult(this));
        realWifiList.clear();
        if(!CollectionUtils.isNullOrEmpty(scanResults)){
            for(int i = 0;i < scanResults.size();i++){
                WifiBean wifiBean = new WifiBean();
                wifiBean.setWifiName(scanResults.get(i).SSID);
                wifiBean.setState(AppContants.WIFI_STATE_UNCONNECT);   //只要获取都假设设置成未连接，真正的状态都通过广播来确定
                wifiBean.setCapabilities(scanResults.get(i).capabilities);
                wifiBean.setLevel(WifiSupport.getLevel(scanResults.get(i).level)+"");
                realWifiList.add(wifiBean);
                //排序
                Collections.sort(realWifiList);
                mWiFiSettingAdapter.AddItem(realWifiList);
            }
        }
    }

    // 清空数据
    private void clearAll(){
        if( realWifiList != null && mWiFiSettingAdapter != null){
            realWifiList.clear();
            mWiFiSettingAdapter.notifyDataSetChanged();
        }
    }
    /**
     * 检查是否已经授予权限
     * @return
     */
    private boolean checkPermission() {
        for (String permission : NEEDED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllPermission = true;
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i : grantResults) {
                if (i != PackageManager.PERMISSION_GRANTED) {
                    hasAllPermission = false;   //判断用户是否同意获取权限
                    break;
                }
            }

            //如果同意权限
            if (hasAllPermission) {
                mHasPermission = true;
                if(WifiSupport.isOpenWifi(NewWiFiSettingActivity.this) && mHasPermission){  //如果wifi开关是开 并且 已经获取权限
                    sortScaResult();
                }else{
                    Toast.makeText(NewWiFiSettingActivity.this,"WIFI处于关闭状态或权限获取失败1111",Toast.LENGTH_SHORT).show();
                }

            } else {  //用户不同意权限
                mHasPermission = false;
                Toast.makeText(NewWiFiSettingActivity.this,"获取权限失败",Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 申请权限
     */
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }
    @Override
    public void WiFiSettingbacak() {
        finish();
    }

    @Override
    public void showOpen() {
        activityNewWifiSettingIvClose.setBackgroundResource(R.drawable.video_player_canvas_open);
    }

    @Override
    public void showcloase() {
        activityNewWifiSettingIvClose.setBackgroundResource(R.drawable.video_player_canvas_close);
    }

    @Override
    public void showProgress() {
        activityNewWifiSettingMyPreogress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hidenProgress() {
        activityNewWifiSettingMyPreogress.setVisibility(View.GONE);
    }
}
